# coding=utf-8
import base64
import json

import requests
import urllib.parse
from Crypto.Cipher import AES

# 加密
def aes_encrypt(key, message):
    padding = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
    txt = AES.new(key.encode(encoding="utf8"), AES.MODE_ECB).encrypt(padding(message).encode(encoding="utf8"))
    return base64.b64encode(txt)

# 解密
def aes_decrypt(key, message):
    unpadding = lambda s: s[:-ord(s[len(s) - 1:])]
    base64_decrypted = base64.decodebytes(message.encode(encoding='utf-8'))
    string = str(AES.new(key.encode(encoding="utf8"), AES.MODE_ECB).decrypt(base64_decrypted), encoding='utf-8')
    return unpadding(string)

#url = "https://dcode-test.cguarantee.com/service-interface-gateway/api/invoke/"
url = "http://zebra.dev.com/service-interface-gateway/api/invoke/"
secret = "e7a87080efba4134ad63efd158aa32e0"
apiName = "身份证二要素验证"
applicationName = "callPythonApi"
stage = "br"
shortName="br"
apiName = base64.b64encode(apiName.encode())
applicationName = base64.b64encode(applicationName.encode())
stage = base64.b64encode(stage.encode())

headers = {
	"apiName": apiName,
	"applicationName": applicationName,
	"stage": stage,
	"periodValidity": "90"
}

# 业务系统参数加密
params = {
	"id": 500235199212260331,
	"name": "曾智"
}
dumps = json.dumps(params)
reqParams = aes_encrypt(secret, dumps)
realReqParams = urllib.parse.quote(reqParams)

realSecret = str(base64.b64encode(secret.encode()), encoding="utf-8")
realurl = url + realSecret

response = requests.post(realurl, headers=headers, json=realReqParams)
print(aes_decrypt(secret,response.text))

